package com.tbvtc.agriculturalcreditchainserver2025.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tbvtc.agriculturalcreditchainserver2025.dto.Cart.*;
import com.tbvtc.agriculturalcreditchainserver2025.dto.consumer.addCartDto;
import com.tbvtc.agriculturalcreditchainserver2025.entity.Crop;
import com.tbvtc.agriculturalcreditchainserver2025.entity.Test;
import com.tbvtc.agriculturalcreditchainserver2025.entity.UserAddress;
import com.tbvtc.agriculturalcreditchainserver2025.exception.FoodException;
import com.tbvtc.agriculturalcreditchainserver2025.mapper.CartMapper;
import com.tbvtc.agriculturalcreditchainserver2025.pojo.ResultPage;
import com.tbvtc.agriculturalcreditchainserver2025.service.*;
import com.tbvtc.agriculturalcreditchainserver2025.utils.CartSelectUtils;

import com.tbvtc.agriculturalcreditchainserver2025.utils.ResultCodeEnum;

import com.tbvtc.agriculturalcreditchainserver2025.constant.RedisConstant;
import com.tbvtc.agriculturalcreditchainserver2025.vo.Cart.*;
import com.tbvtc.agriculturalcreditchainserver2025.vo.ConsumerVo.addCartVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private CartSelectUtils cartSelectUtils;
    @Resource(name = "cartRedisTemplate")
    private RedisTemplate<String, CartSelectUserByUserId> redisTemplate;
    @Resource
    private ICropService cropService;
    @Resource
    private ITestService testService;
    @Resource
    private IUserAddressService userAddressService;
    @Resource
    private IUserService userService;


    @Override
    public addCartVo addCart(addCartDto addCartDto) {
        addCartVo addCartVo = cartMapper.selectCart(addCartDto.getUserId(), addCartDto.getGoodId());
        if (addCartVo == null) {
            addCartDto.setNum(addCartDto.getNum());
            addCartDto.setTime(LocalDateTime.now());
            addCartDto.setPhone(userService.getById(addCartDto.getUserId()).getPhone());
            cartMapper.addCart(addCartDto);
            addCartVo addCartVo2 = cartMapper.selectCart(addCartDto.getUserId(), addCartDto.getGoodId());
            return addCartVo2;
        }
        cartMapper.updateCartNum(addCartVo.getId(), addCartVo.getNum() + addCartDto.getNum());
        // 根据userid和goodid查询购物车
        addCartVo addCartVo1 = cartMapper.selectCart(addCartDto.getUserId(), addCartDto.getGoodId());
        return addCartVo1;
    }

    @Override
    public void addCartNum(Integer id) {
        try {
            Integer num = cartMapper.selectNum(id);
            num++;
            cartMapper.updateCartNum(id, num);
        } catch (NullPointerException e) {
            //抛出购物车单号不存在
            throw new FoodException(ResultCodeEnum.APP_CART_NOT_EXIST);
        }

    }


    @Override
    public Integer updateCartNum(Integer count1, Integer id) {
        Integer num = cartMapper.selectCartNum(id);

        if (count1 <= 0) {
//                  throw new leaseException(ResultCodeEnum.APP_CART_NUM_ERROR);
            cartMapper.removeCart(id);
            return 0;
        }
        cartMapper.updateCartNum(id, count1);
        return count1;
    }

    @Transactional
    @Override
    public void addAddress(cartAddressDto cartAddressDto) {
        if (cartAddressDto.getIsDefault() == 1) {
            // 如果设为默认地址，先清空该用户原有默认地址
            cartMapper.updateUserAddressSetNonDefault(cartAddressDto.getUserId());
        }
        cartMapper.addAddress(cartAddressDto);
    }

    @Override
    public void clearCart(Integer userId) {
        List<Integer> list = cartMapper.selecIdByUserIdtCart(userId);
        list.forEach(id -> {
            cartMapper.clearCart(id);
        });

    }

    @Override
    public cartIdAndPriceVo settlementCart(SettlementCartDto settlementCartDto) {
        List<cartPriceVo> list = cartMapper.selectCartIds(settlementCartDto); // 获取购物车价格和数量
        BigDecimal totalPrice = new BigDecimal(0);
        for (cartPriceVo cartPriceVo : list) {
            Integer num = cartPriceVo.getNum();
            BigDecimal price = cartPriceVo.getPrice();
            totalPrice = totalPrice.add(price.multiply(new BigDecimal(num)));
        }
        cartOrderVo cartOrderVo = new cartOrderVo();
        cartOrderVo.setUserId(settlementCartDto.getUserId());
        cartOrderVo.setTotalPrice(totalPrice);
        cartOrderVo.setStatus(0);
        cartOrderVo.setTime(LocalDateTime.now());
        cartMapper.settlementCart(cartOrderVo); // 添加订单
        cartIdAndPriceVo cartIdAndPrice = new cartIdAndPriceVo(); // 封装订单id和价格
        cartIdAndPrice.setOrderId(cartOrderVo.getId());
        cartIdAndPrice.setPrice(totalPrice);

        return cartIdAndPrice;
    }

    @Override
    public void removeCart(Integer cartId) {
        cartMapper.removeCart(cartId);
    }

    //    @Override
//    public ResultPage<GroupData> findOrderById(UserOrderLimitDot userOrderLimitDot) {
//        String phone = cartMapper.selectPhoneById(userOrderLimitDot.getId());
//        PageHelper.startPage(userOrderLimitDot.getPage(), userOrderLimitDot.getPageSize()); // 分页
//        List<GroupData> list = cartMapper.findOrderByPhone(phone);
//        Page<GroupData> page = (Page<GroupData>) list;
//        return new ResultPage(page.getTotal(), page.getResult());
//
//    }
    @Override
    public ResultPage<GroupData> findOrderById(UserOrderLimitDot userOrderLimitDot) {
        String phone = cartMapper.selectPhoneById(userOrderLimitDot.getId());
//    PageHelper.startPage(userOrderLimitDot.getPage(), userOrderLimitDot.getPageSize()); // 分页
        List<GroupData> list = cartMapper.findOrderByPhone(phone, userOrderLimitDot.getStatus());
        PageInfo<GroupData> pageInfo = new PageInfo<>(list);
        return new ResultPage<>(pageInfo.getTotal(), pageInfo.getList());
    }


    // Service 层
//    public PageInfo<GroupedData> findOrderById(UserOrderLimitDot userOrderLimitDot) {
//        String phone = cartMapper.selectPhoneById(userOrderLimitDot.getId());
//        // 启动分页
//        PageHelper.startPage(userOrderLimitDot.getPage(), userOrderLimitDot.getPageSize());
//        List<GroupedData> orderByPhone = cartMapper.findOrderByPhone(phone);
//        List<GroupedData> rawData1 = orderByPhone;
//
//        // 手动处理分页总数（PageHelper 不支持自动计算 GROUP BY 后的总数）
////        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(rawData);
//
//        // 解析 JSON 数组为对象列表
//        ObjectMapper objectMapper = new ObjectMapper();
//        List<GroupedData> resultList = new ArrayList<>();
//        for (Map<String, Object> row : rawData) {
//            GroupedData data = new GroupedData();
//            data.setCreateTime((String) row.get("createTime"));
//            data.setUsername((String) row.get("username"));
//            data.setAddress((String) row.get("address"));
//
//            // 解析 JSON 字符串为 List<Item>
//            String itemsJson = (String) row.get("items");
//            try {
//                List<Item> items = objectMapper.readValue(itemsJson, new TypeReference<List<Item>>() {});
//                data.setItems(items);
//            } catch (Exception e) {
//                data.setItems(Collections.emptyList());
//            }
//            resultList.add(data);
//        }
//
//        // 手动构造分页结果
//        PageInfo<GroupedData> resultPage = new PageInfo<>(resultList);

    /// /        resultPage.setTotal(pageInfo.getTotal());
//        return resultPage;
//    }
    @Override
    public void pay(SettlementCartDto settlementCartDto) {
        //先删除购物车
        cartMapper.ClearCart(settlementCartDto);
        //查询订单添加到发货表
        //获取购物车价格和数量和手机号
        List<CartSelectPhoneAndGoodByUserId> list = cartMapper.selectCartPhoneAndGoodByUserId(settlementCartDto);
        Set<String> set = new HashSet<>();
        list.forEach(s -> {
            set.add(s.getPhone());
        });
        System.out.println(set);
        LinkedHashMap<String, List<CartSelectPhoneAndGoodByUserId>> collect = list.stream()
                // 过滤掉phone为空的数据（按需添加）
                .filter(item -> item.getPhone() != null && !item.getPhone().isEmpty())
                // 根据phone字段分组
                .collect(Collectors.groupingBy(
                        CartSelectPhoneAndGoodByUserId::getPhone,
                        // 可选：保持插入顺序的LinkedHashMap
                        LinkedHashMap::new,
                        Collectors.toList()
                ));
        set.forEach(phone -> {
            List<CartSelectPhoneAndGoodByUserId> cartSelectPhoneAndGoodByUserIds = collect.get(phone);
            cartSelectUtils.selectPhoneAndGoodByUserId(cartSelectPhoneAndGoodByUserIds, settlementCartDto.getUserId(), 1);
        });
        //删除购物车里的已经结算东西
        List<Integer> cartIds = settlementCartDto.getCartIds();
        cartIds.forEach(id -> {
            cartMapper.removeCart(id);
        });
    }

    @Override
    public List<CartSelectUserByUserId> UserfindUserOrderById(Integer userId, Integer state) {
        List<CartSelectUserByUserId> list = cartMapper.selectCartUserByUserId(userId, state);
        return list;
    }


    @Override
    public void cancelPayCart(SettlementCartDto settlementCartDto) {
        //先删除购物车
       cartMapper.ClearCart(settlementCartDto);

        //查询订单添加到发货表
        // 获取购物车价格和数量和手机号
        List<CartSelectPhoneAndGoodByUserId> list = cartMapper.selectCartPhoneAndGoodByUserId(settlementCartDto);
        Set<String> set = new HashSet<>();
        list.forEach(s -> {
            set.add(s.getPhone());
        });
        System.out.println(set);
        LinkedHashMap<String, List<CartSelectPhoneAndGoodByUserId>> collect = list.stream()
                // 过滤掉phone为空的数据（按需添加）
                .filter(item -> item.getPhone() != null && !item.getPhone().isEmpty())
                // 根据phone字段分组
                .collect(Collectors.groupingBy(
                        CartSelectPhoneAndGoodByUserId::getPhone,
                        // 可选：保持插入顺序的LinkedHashMap
                        LinkedHashMap::new,
                        Collectors.toList()
                ));
        set.forEach(phone -> {
            List<CartSelectPhoneAndGoodByUserId> cartSelectPhoneAndGoodByUserIds = collect.get(phone);
            cartSelectUtils.selectPhoneAndGoodByUserId(cartSelectPhoneAndGoodByUserIds, settlementCartDto.getUserId(), 0);
        });
        //删除购物车里东西
        //删除购物车里的已经结算东西
        List<Integer> cartIds = settlementCartDto.getCartIds();
        cartIds.forEach(id -> {
            cartMapper.removeCart(id);
        });
        //查询所有订单放大redis中
        List<CartSelectUserByUserId> cartSelectUserByUserIds = UserfindUserOrderById(settlementCartDto.getUserId(), 0);
        cartSelectUserByUserIds.forEach(s -> {
            redisTemplate.opsForValue().set(RedisConstant.TASK_DATA_KEY + s.getOrderId(), s, 15, TimeUnit.MINUTES);
        });


    }

    @Override
    public void payOrder(String orderId) {
        Integer i = cartMapper.payOrder(orderId, LocalDateTime.now());
        if (i == 0) {
            throw new FoodException(ResultCodeEnum.APP_ORDER_NOT_EXIST_ERROR);
        }
    }


    @Override
    public void updateUserAddressSetNonDefault(Integer addressId) {
        UserAddress userAddress = userAddressService.getById(addressId);
        Integer userId = userAddress.getUserId();
        userAddressService.update(new LambdaUpdateWrapper<UserAddress>()
                .eq(UserAddress::getUserId, userId)
                .set(UserAddress::getIsDefault, 0)
        );
        userAddressService.update(new LambdaUpdateWrapper<UserAddress>()
                .eq(UserAddress::getAddressId, addressId)
                .set(UserAddress::getIsDefault, 1)
        );
    }

    @Override
    public List<addressItem> selectAddressByUserId(Integer userId) {
        List<addressItem> list = cartMapper.selectAddressByUserId(userId);
        return list;
    }

    @Override
    public GroupedData findOrderByOrderId(String orderId) {
        GroupedData groupedData = cartMapper.findOrderByOrderId(orderId);
        List<Test> list = testService.list(new LambdaQueryWrapper<Test>().eq(Test::getOrderId, orderId));
        //查询用户手机号
        String userId = cartMapper.selectPhoneByOrderId(groupedData.getItems().get(0).getId());
        String phone = cartMapper.selectPhoneById(Integer.parseInt(userId));
        groupedData.setUsername(list.get(0).getUsername());
        groupedData.setPhone(phone);
        return groupedData;
    }

    @Override
    public void deleteAddress(Integer addressId) {
        cartMapper.deleteAddress(addressId);
    }

    @Override
    public void updateAddress(CartUpdataAddressDto cartUpdataAddressDto) {
        UserAddress addressServiceById = userAddressService.getById(cartUpdataAddressDto.getAddressId());
        UserAddress userAddress = BeanUtil.copyProperties(cartUpdataAddressDto, UserAddress.class);
        if (cartUpdataAddressDto.getIsDefault() == 1) {
            //说明是默认值
            userAddressService.update(new LambdaUpdateWrapper<UserAddress>()
                    .eq(UserAddress::getUserId, addressServiceById.getUserId())
                    .set(UserAddress::getIsDefault, 0)
            );
        }
        userAddressService.updateById(userAddress);
    }

    @Override
    public void confirmDelivery(String orderId, String logisticsInfo, String expressCompany) {
        Integer result = cartMapper.addLogisticsInfo(orderId, logisticsInfo, expressCompany);
        if (result == 0) {
            throw new FoodException(ResultCodeEnum.APP_ORDER_NOT_EXIST);
        }

    }

    @Override
    public Long findOrderTime(String orderId) {
        //获取redis中的数据的剩余时间
        Long ttl = redisTemplate.getExpire(RedisConstant.TASK_DATA_KEY + orderId, TimeUnit.SECONDS);
//        CartSelectUserByUserId cartSelectUserByUserId = redisTemplate.opsForValue().get(RedisConstant.TASK_DATA_KEY + orderId);
        return ttl;

    }

    @Override
    public List<CartInfoDto> getCartInfo(Integer userId) {
        List<addCartVo> cartInfo = cartMapper.getCartInfo(userId);
        if (cartInfo == null) {
            throw new FoodException(ResultCodeEnum.CART_EMPTY);
        }
        List<CartInfoDto> cartInfoDtos = BeanUtil.copyToList(cartInfo, CartInfoDto.class);
        Set<Integer> goodIds = cartInfoDtos.stream().
                map(CartInfoDto::getGoodId).
                filter(Objects::nonNull).
                collect(Collectors.toSet());
        List<Crop> cropList = cropService.listByIds(goodIds);
        Map<Integer, Crop> map = cropList.stream().collect(Collectors.toMap(Crop::getId, crop -> crop));
        cartInfoDtos.forEach(s -> {
            Crop crop = map.get(s.getGoodId());
            crop.setId(s.getId());
            BeanUtil.copyProperties(crop, s);
        });

        return cartInfoDtos;

    }


}
